<?php
class ProductCategoriesMapper //extends SimpleWebResponseInterpretator
{
    private $categoriesXML;
    private $updatedProductCounter;                   
    private $addedProductCounter;
    
    public $response;
    
   public function __construct($response)
   {
        $this->response = $response->getContent();       
        $this->response = new SimpleXMLElementExtended( $this->response );
        
        //variables
        $this->updatedProductCounter = 0;
        $this->addedProductCounter = 0;
        //$this->response = new SimpleXMLElementExtended( $response );
   }
	
   public function execute( $response )
   {
        //parent::execute( $response );
	
        //return $this->getData();
                
	//$this->setResponseArray($this->convertResponse2Array());
	//unset($this->response);
   }
   
   public function getSXMLArray()
   {
       //return $this->response->items->item[1]->getAttribute("name");;       
   }
   
   public function cleanDB() //compare data in DB and in Directo, if in DB more data witch Directo, clean DB
   {
    
       return this.compareXMLDataAndDataInDB();
       
   }
   
   public function writeProductsInDB($attr)
   {
       $addedProductCounter = 0;
       $updatedProductCounter = 0;
       $errorCount = 0;
               
       foreach( $this->xmlObj()->items as $key=>$value )
       {
        foreach( $value as $inKey=>$inValue )
        {
         if($attr == "last")
         {
          $d = $this->convertDate($inValue['ts']);
          $yesterdayTime = time() - 3600 *24;
          
          if( $d > $yesterdayTime)
          {   
           $codesArray = $this->searchCodeInDB($inValue['code']);
          
           $this->updateAndAddProducts($codesArray);
          }  
         }
         elseif($attr == "all")
         {
          $codesArray = $this->searchCodeInDB($inValue['code']);
          
          $this->updateAndAddProducts($codesArray);
         }
        }
       }
      
       return array($this->getAddedProductsCount(), $this->getUpdatedProductsCount());
   }
   
   public function compareXMLDataAndDataInDB()
   {
       // if data in DB exist but in XML not, must delete data in DB
       
       $deletedProductCounter = 0;
       
       $allProductsInBD = $this->getAllProducts();
       
       foreach( $allProductsInBD as  $key )
       {
           $compareCounter = false;
           
           foreach( $this->xmlObj()->items as $xmlKey=>$xmlValue )
           {
                foreach( $xmlValue as $inKey=>$inValue )
                {               
                    if( $key['code'] == $inValue['code'] )
                    {
                        $compareCounter = true;                        
                    }
                }                
           }
           
           if( $compareCounter === false )
           {
               $this->deleteProductFromDB( $key['id'] );               
               $deletedProductCounter++;               
           }           
       }
       
       return $deletedProductCounter;
   }
   
   private function getAllProducts()
   {
       $query = Doctrine_Query::create()
        ->from('Product p')
	->select('p.code');

        $data = $query->fetchArray();
        
        return $data;       
   }
   
   public function searchCodeInDB($code)
   {
       
       $query = Doctrine_Query::create()
        ->from('Product p')
	->select('p.code')
	->where('p.code = ?', $code);

        $data = $query->fetchArray();

        return $data;
   }
   
   public function updateRowInDB($code, $prodArray)
   {        
       $obj = Doctrine_Query::create()
            ->select('*')
            ->from('Product')
            ->where('code = ?', $code)
            ->fetchOne();
            $obj->synchronizeWithArray( $prodArray );
            $obj->save();  
   }
   
   public function addProductInDB($prodArray)   //$this->addProductInDB( array($inValue['code'], $inValue['name'], $inValue['discount_price'] ) ); //code, name, discount_price, weight
   {
       $addNewProduct = new Product();
       $addNewProduct['code'] = $prodArray['code'];
       $addNewProduct['Translation']['et']['name'] = $prodArray['name'];
       $addNewProduct['price'] = $prodArray['price'];
       $addNewProduct['discount_price'] = $prodArray['discount_price'];
       //$addNewProduct['weight'] = $prodArray['weight'];
       
       $addNewProduct->save();
       
       //return true; 
   }
   
   public function convertDate($date)
   {
       if($date)
       {       
           $date_elements  = explode("-", $date);

           $time = mktime(0,0,0,$date_elements[1],$date_elements[2],$date_elements[0]);
           //$time = mktime (0,0,0,12,20,2009);
           return $time;
       }
       else
       {
           return time();
       }
           
   }
   
   private function deleteProductFromDB($prod_id)
   {   
       Doctrine_Query::create()
        ->delete('Product p')
        ->where('p.id = ?', $prod_id )
        ->execute();       
   }
   
   public function initSimpleXMLObj()
   {
        $this->categoriesXML = $this->response;       
        return $this->categoriesXML;
   }
   
   public function xmlObj()
   {
       return $this->response;       
   }
   
   public function getAddedProductsCount()
   {
       return $this->addedProductCounter;       
   }
   
   public function getUpdatedProductsCount()
   {
       return $this->updatedProductCounter;
   }
   
   private function addAddedProductCount()
   {
       $this->addedProductCounter++;
   }
   
   private function addUpdatedProductCount()
   {
       $this->updatedProductCounter++;                   
   }
   
   
   public function updateAndAddProducts($codesArray)
   {
    if( count($codesArray) < 2  )
    {                                      
     $codeInDB = $codesArray[0]['code'];
     
     if( $codeInDB ) //component is exist
     {
      $updateArray = array( 'Translation' => array('et' => array('name' => $inValue['name'] )) , 'price'=>$inValue['price'], 'discount_price'=>$inValue['discount_price']);
                           
      $this->updateRowInDB( $codeInDB, $updateArray);
      $this->addUpdatedProductCount();     
     }
     else // component not exist in DB
     {                                 
      //$prodArray = array( 'code'=>'33', 'name'=>'Pablo', 'discount_price'=>'200' ); 
      $this->addProductInDB( array( 'code'=>$inValue['code'], 'name'=>$inValue['name'], 'price'=>$inValue['price'], 'discount_price'=>$inValue['discount_price'], 'weight'=>$inValue['weight']) );
      $this->addAddedProductCount();      
     }    
    }    
   }
   
   public function writeProductGroupsInDB()
   { 
    foreach( $this->xmlObj()->items as $key=>$value )
    {
     foreach( $value as $inKey=>$inValue )
     {                  
      $group = $inValue['ART_TUUP'];
         
       if($group )
       {
        //$this->searchGroupNameInDB();             
       }
       else
       {
                   
       }          
      }
    }
   }
   
   public function searchGroupNameInDB($groupCode)
   {
       
       
   }
         
}